<template>
  <el-container class="login-container">
    <div class="login">
      <div class="login-panel">
        <div class="logo">简知IM聊天系统</div>
        <el-form :model="loginForm" :rules="loginRules" ref="loginForm">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" prefix-icon="el-icon-user" placeholder="用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" prefix-icon="el-icon-lock" type="password" @keyup.enter.native="toLogin" placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item v-if="isRegister" prop="nickname">
            <el-input v-model="loginForm.nickname" prefix-icon="el-icon-s-custom" placeholder="昵称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="login-btn" @click="isRegister ? toRegister() : toLogin()">
              {{ isRegister ? '注册' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
        <p class="tip">
          {{ isRegister ? '已有账号?' : '没有账号?' }}
          <span class="switch-link" @click="changeType">{{ isRegister ? '去登录' : '注册' }}</span>
        </p>
      </div>
    </div>
  </el-container>
</template>

<script>
import "./index.less";
import { mapState, mapActions } from "vuex";

export default{
  data(){
    return {
      loginForm: {
        username: "",
        password: "123456",
        nickname: ""
      },
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ]
      }
    };
  },
  mounted: function(){
    // 自动判断是注册还是登录页面
    if (window.location.pathname === '/register'){
      console.log('注册页面加载');
      this.setRegisterFlag(true);
    }else if(window.location.pathname === '/login'){
      console.log('登录页面加载');
      this.setRegisterFlag(false);
      
      // 检查是否有存储的用户信息
      const userInfo = localStorage.getItem("userInfo") && JSON.parse(localStorage.getItem("userInfo"));
      if(userInfo && userInfo.userId){
        this.loginForm.username = userInfo.userId;
      }
    }
  },
  computed: {
    isRegister(){
      return this.$store.state.login.isRegister;
    },
  },
  methods: {
    ...mapActions([
      "onLogin", 
      "setRegisterFlag", 
      "onRegister",
      "onLogout", 
      "onGetFirendBlack", 
      "initChatState",
      "addfirend",
      "acceptSubscribe"
    ]),
    
    async toLogout2() {
      await this.onLogout();
      await this.initChatState();
    },
    
    toLogin(){
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          let username = this.loginForm.username.toLowerCase();
          let password = this.loginForm.password;
          
          // 检查是否有存储的用户信息
          const userInfo = localStorage.getItem("userInfo") && JSON.parse(localStorage.getItem("userInfo"));
          
          if(userInfo && userInfo.userId){
            // 使用存储的用户ID登录
            this.onLogin({
              username: userInfo.userId.toLowerCase(),
              password: '123456'
            });
          } else {
            // 使用表单填写的信息登录
            this.onLogin({
              username: username,
              password: password
            });
          }
        }
      });
    },
    
    async toRegister(){
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          let username = this.loginForm.username.toLowerCase();
          let password = this.loginForm.password;
          let nickname = this.loginForm.nickname || username;
          
          console.log('开始注册用户:', username);
          
          await this.onRegister({
            username: username,
            password: password,
            nickname: nickname,
          });
          
          console.log('注册完成，准备登录');
        }
      });
    },
    
    changeType(){
      this.setRegisterFlag(!this.isRegister);
    }
  }
};
</script>

<style lang="less" scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.login {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
  
  .login-panel {
    background: #fff;
    border-radius: 8px;
    padding: 30px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .logo {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 30px;
      color: #409EFF;
    }
    
    .login-btn {
      width: 100%;
    }
    
    .tip {
      font-size: 14px;
      color: #606266;
      margin-top: 16px;
      
      .switch-link {
        color: #409EFF;
        cursor: pointer;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
}
</style>
